import { Button, Pagination, Space, Table, Tag } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import React, { useState, useEffect, forwardRef } from 'react';
import axios from '../../axios';
import xlsx from './xlsx';
import './dataTable.d'
import './dataTable.scss'
const { Column, ColumnGroup } = Table;
type Props = {
  ajax?: Ajax //接口的结构
  key?: string //传进来的key用于多选判断数据的唯一性
  CheckChange?: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => void //多选或者单选的触发事件
  selectType?: 'checkbox' | 'radio' //单选多选类型 -- 默认为没有
  isIndex?: boolean //是否显示序号
  inTableData: InTableData
  tableClickConfig?: (obj: TableClickConfig) => void
  getCheckboxProps?: (record: any) => ({ disabled: boolean, name: string }) //禁止那条数据不能选中
  inSearchCallback?: <T>(e: T) => ({ [key: string]: T })//参数返回的数据默认是data.list
}
const DataTable = forwardRef((props: Props, onref) => {
  const currentObj = { exportExcel }
  // @ts-ignore
  onref.current = currentObj
  const {
    inTableData,
    ajax,
    selectType,
    isIndex = true,
    inSearchCallback = (res: any) => {
      return res.list
    },
    getCheckboxProps = (record: any) => ({
      disabled: record.ssdw === '民治街道', // 是否禁用
      name: record.name,
    }) } = props
  // const [data, setData] = useState(inTableData.tData)
  const [head, setHead] = useState(inTableData.tHead)
  const [inTableDatas, setInTableDatas] = useState(inTableData)
  const [total, setTotal] = useState(10)
  const [pagination, setPagination] = useState({
    current: ajax?.data.pageNumber,
    pageSize: ajax?.data.pageSize,
  })
  const [selectionType,] = useState<'checkbox' | 'radio'>(selectType);
  // 分页数据发生变化后调用接口和初始化
  useEffect(() => {
    heardInit()
    if (ajax) {
      ajaxInit()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination])
// 初始化表头
  function heardInit() {
    setHead(state => {
      // 获取表头中的callback回调根据参数出现按钮
      for (let item of state) {
        if (item.callback) {
          item.render = ((v, row) => {
            return (
              item.callback(v, row).map(val => {
                return (<Button type="link" key={val.type} onClick={() => { onClick(val) }}>{val.label}</Button>)
              })
            )
          })
        }
      }
      // 是否需要出现序号  默认为出现
      if (!isIndex) return [...state]
      // 判断第一条是否是序号 如果是则不需要添加
      if (state[0].key === 'index') {
        state[0].render = function (text, record, index) {
          return `${(pagination.current - 1) * (pagination.pageSize) + (index + 1)}`
        }
        return [...state]
      }
      // 不是 则添加
      state.unshift({
        title: '序号',
        key: 'index',
        render: (text, record, index) => `${index + 1}`

      })
      inTableData.tHead = state
      return [...state]
    })

  }
  function onClick(item) {
    props.tableClickConfig({ type: item.type, rowData: item })

  }
  // 初始化接口
  async function ajaxInit() {
    const param = {
      ...ajax.data,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize
    }
    const { data } = await axios[ajax.method](ajax.url, param)
    const datas = inSearchCallback(data)
    setInTableDatas(state => {
      state.total = data.total

      return { ...state }
    })
    getIndex(datas)
  }
  // 初始化序号
  function getIndex(data) {
    // 更新数据
    setInTableDatas((state) => {
      state.tData = data
      return { ...state }
    })
    inTableData.tData = data
  }
  // 点击事件
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      props.CheckChange(selectedRowKeys, selectedRows)
    },
    getCheckboxProps,
  };
  // 判断是否出现单选多选
  function getRowSelection() {
    if (selectType) {
      return {
        type: selectionType,
        ...rowSelection,
      }
    }
    return null
  }
  // 分页点击事件
  function paginationChange(current, pageSize) {
    setPagination(() => {
      return { current, pageSize }
    })
  }
  // 表格导出
  function exportExcel(name: string) {
    console.log(inTableDatas.tData);

    // @ts-ignore
    xlsx.exportExcelRef(name, head, inTableDatas.tData)
  }

  return (
    <div className='dataTable'>
      <Table rowKey={(record, index) => index + 1} scroll={{ y: '75vh' }} rowSelection={getRowSelection()} dataSource={inTableDatas.tData} columns={head} pagination={false} >
      </Table>
      <div className='pagination'>
        <Pagination showQuickJumper showSizeChanger defaultCurrent={1} total={inTableData.total || 10} onChange={paginationChange} />
      </div>
    </div>


  )
})

export default DataTable;